package com.itheima.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.common.UserHolder;
import com.itheima.ydd.dto.ConfigDto;
import com.itheima.ydd.dto.ConfigDto1;
import com.itheima.ydd.dto.SysUserInfo;
import com.itheima.ydd.entity.Config;
import com.itheima.ydd.entity.Menu;
import com.itheima.ydd.entity.User;
import com.itheima.ydd.mapper.ConfigMapper;
import com.itheima.ydd.service.*;
import com.itheima.ydd.service.ConfigService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yan.zhou
 * @since 2022-02-21
 */
@Service
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements ConfigService {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;

    private static HashMap<String,String> configName = new HashMap<>();
    static {
        configName.put("base","基础配置");
        configName.put("system","系统设置");
        configName.put("custom","其他设置");
    }

    @Override
    public Map<String, Object> profile() {
        HashMap<String, Object> map = new HashMap<>();
        //1. 查询用户信息
        String userId = UserHolder.getUserId();
        User user = userService.getById(UserHolder.getUserId());
        SysUserInfo userInfo = new SysUserInfo();
        BeanUtils.copyProperties(user, userInfo);

        //查询用户角色id集合: role_id
        String[] rowIds = user.getRole_id().replace("[", "")
                .replace("]", "")
                .replace("\"", "")
                .split(",");
        List<String> ids = new ArrayList<>();
        Collections.addAll(ids, rowIds);
        userInfo.setRole_id(ids);
        map.put("userInfo", userInfo);

        //查询用户角色名称集合: role_id
        String role_id = UserHolder.get().getRole_id();
        List<String> roleNameList = roleService.roleNameList(role_id);
        userInfo.setRolename(roleNameList);

        //2. 查询角色菜单集合
        List<Menu> menuList = menuService.menuList(role_id);
        map.put("menuList", menuList);


        //region #dictsList 不知道干嘛用的，结果直接为原本数据
        HashMap<String, Object> dictsList = new HashMap<>();
        HashMap<String, String> interface_type = new HashMap<>();
        interface_type.put("get", "get");
        interface_type.put("post", "post");
        dictsList.put("interface_type", interface_type);

        ArrayList<String> table_type = new ArrayList<>();
        table_type.add("单表");
        table_type.add("主表");
        table_type.add("附表");
        table_type.add("树结构表");
        dictsList.put("table_type", table_type);

        ArrayList<String> order_type = new ArrayList<>();
        order_type.add("支付宝");
        order_type.add("微信");
        dictsList.put("order_type", order_type);

        ArrayList<String> report_type = new ArrayList<>();
        report_type.add("正常报告");
        report_type.add("异常报告");
        dictsList.put("report_type", report_type);

        HashMap<String, String> theme = new HashMap<>();
        theme.put("ace", "ACE风格");
        dictsList.put("theme", theme);
        map.put("dictsList", dictsList);

        ArrayList<String> btn = new ArrayList<>();
        btn.add("*");
        map.put("btnList",btn);

        return map;
    }

    @Override
    public Map<String, Object> all() {
        Map<String, Object> map = new HashMap<>();
        //配置树查询
        ArrayList<ConfigDto> list = new ArrayList<>();
        //配置参数
        ArrayList<Config> allData = new ArrayList<>();
        //表单参数
        HashMap<String,Object> configFrom = new HashMap<>();
        //表单规则
        HashMap<String,String> configRules = new HashMap<>();

        QueryWrapper<Config> lqw = new QueryWrapper<>();
        lqw.lambda().select(Config::getTab_value,Config::getGroup_value);
        lqw.lambda().groupBy(Config::getTab_value);
        //获取一级属性列表
        List<Config> tabList = this.list(lqw);
        //遍历一级属性,获取下级属性
        for (Config tabConfig : tabList) {
            String key = tabConfig.getTab_value();
            System.out.println("tab_value = "+key);
            //创建一级属性对象
            ConfigDto configDto = new ConfigDto();
            configDto.setKey(key);
            configDto.setName(configName.get(key));
            //根据一级属性对象查找二级属性对象
            configDto = getChildren(configDto,allData,configFrom,configRules);
            //将一级属性添加到列表
            list.add(configDto);
        }
        //获取configfrom


        //HashMap<String, Object> map = new HashMap<>();
        map.put("allData",allData);
        map.put("configForm",configFrom);
        map.put("configRules",configRules);
        map.put("list",list);
        return map;
    }

    /**
     * @Author 16372
     * @Description //TODO 获取二级配置菜单
     * @Date 15:58 2022/2/27
     * @Param [configDto]
     * @return com.itheima.ydd.dto.ConfigDto
     **/
    private ConfigDto getChildren(ConfigDto configDto,ArrayList allData,HashMap configFrom,HashMap configRules){
        //获取一级属性名特征 Tab_value
        QueryWrapper<Config> lqw = new QueryWrapper<>();
        System.out.println("configDto.getKey() = " + configDto.getKey());
        //根据一级属性特征 获取二级属性列表
        lqw.lambda().select(Config::getGroup_value);
        lqw.lambda().eq(Config::getTab_value,configDto.getKey());
        lqw.lambda().groupBy(Config::getGroup_value);
        List<Config> list = this.list(lqw);
        //遍历二级属性列表,查询对应三级属性
        for (Config config : list) {
            //创建dto 装载三级属性属性
            ConfigDto1 dto = new ConfigDto1();
            dto.setName(config.getGroup_value());
            ConfigDto1 data = getData(dto, allData,configFrom,configRules);
            //将三级属性封装到二级属性的子列表中
            configDto.addChildren(data);
        }
        //根据二级属性去查三级属性
        //getData(configDto,allData,configFrom,configRules);
        return configDto;
    }


    /**
     * @Author 16372
     * @Description //TODO 获取具体配置
     * @Date 15:53 2022/2/27
     * @Param [config]
     * @return java.util.List<com.itheima.ydd.entity.Config>
     **/
    private ConfigDto1 getData(ConfigDto1 config,ArrayList allData,HashMap configFrom,HashMap configRules) {
        LambdaQueryWrapper<Config> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Config::getGroup_value,config.getName())
                        .orderByAsc(Config::getId);
        System.out.println("Config_value = " + config.getName());
        List<Config> list = this.list(lqw);
        for (Config config1 : list) {
            String  value = (String) config1.getConfig_value();
            if (value != null && value != ""){
                try {
                    ArrayList<Map> objects = new ArrayList<>();
                    String[] split = value.split("&");
                    for (String s : split) {
                        String[] split1 = s.split("=");
                        HashMap hashMap = new HashMap();
                        hashMap.put("label",split1[0]);
                        hashMap.put("value",split1[1]);
                        objects.add(hashMap);
                    }
                    config1.setConfig_value(objects);
                } catch (Exception e) {

                }
            }

        }
        config.setData(list);
        allData.addAll(list);
        for (Config con : list) {
            configFrom.put(con.getAttr_key(),con.getAttr_value());
            if (con.getValidator() != null && con.getValidator() != "" && !con.getValidator().isEmpty()){
                configRules.put(con.getAttr_key(),con.getValidator());
            }
        }
        return config;
    }
}
